package com.lucky.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
@Order(98)
public class SpringUtil implements ApplicationContextAware {

	private static Logger logger = LoggerFactory.getLogger(SpringUtil.class);
    private static ApplicationContext applicationContext = null;
   
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

    public static Map<String, ?> getBeans(Class<?> class1) {
        return applicationContext.getBeansOfType(class1);
    }

    public static <T> T getBean(Class<T> type) throws BeansException {
        return applicationContext.getBean(type);
    }

    public static <T> T getBean(String beanName, Class<T> type) throws BeansException {
        return applicationContext.getBean(beanName, type);
    }

    public static String getToken(HttpServletRequest request) {
        Cookie[] cookie = request.getCookies();
        if (cookie != null) {
            for (Cookie cook : cookie) {
                if (cook.getName().equals("SESSION") && StringUtils.isNotEmpty(cook.getValue())) {
                    return cook.getValue();
                }
            }
        }
        return null;
    }
}
